package com.qf.lja.servlet;

import com.qf.lja.dao.CartDao;
import com.qf.lja.dao.ProductDao;
import com.qf.lja.enity.Cart;
import com.qf.lja.enity.Product;
import com.qf.lja.enity.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;


@WebServlet(urlPatterns = "/addCart.do")
public class AddCartServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        //字符集
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");

        //判断是否登录
        HttpSession session = req.getSession();
        User user = (User) session.getAttribute("user");

        if (user == null) {
            System.out.println("user null");
            req.getRequestDispatcher("/login.jsp").forward(req, resp);
        }

        //
        Integer productId = Integer.parseInt(req.getParameter("productId"));
        Integer userId = user.getUserId();

        System.out.println("productId:" + productId);
        System.out.println("userId:" + userId);


        CartDao cartDao = new CartDao();
        Cart cart = cartDao.findByProductIdAndUserId(productId, userId);

        System.out.println("cart" + cart);

        System.out.println(cart);
        if (cart != null) {
            System.out.println("update cart");
            cart.setProductQuantity(cart.getProductQuantity() + 1);
            cartDao.updateCart(cart);
        } else {

            ProductDao productDao = new ProductDao();
            Product product = productDao.findByProductId(productId);

            System.out.println(product);
            System.out.println("add cart");
            //添加
            cart = new Cart();
            cart.setProductId(productId);
            cart.setUserId(userId);
            cart.setProductQuantity(1);
            cart.setProduct(product);
            cartDao.addCart(cart);
        }
        req.getRequestDispatcher("/cartSuccess.jsp").forward(req, resp);
    }
}